//
//  AddQuestionViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2018/1/1.
//  Copyright © 2018年 YRX. All rights reserved.
//

#import "AddQuestionViewController.h"
#import "UIView+Extension.h"
#import "YKTextView.h"
#import "Definition.h"
#import "ISRDataHelper.h"
#import "IAMetaDataReader.h"
#import "IASubjectItem.h"

@interface AddQuestionViewController () <UITextViewDelegate>

@property (nonatomic, copy) NSString *subjectName;
@property (nonatomic, strong) YKTextView *questionTextView;
@property (nonatomic, strong) YKTextView *answerTextView;
@property (nonatomic, strong) UIButton *accessoryButton;

@property (nonatomic, strong) YKTextView *selectedTextView;

@property (nonatomic, strong) NSMutableString *speechContent;

@end

@implementation AddQuestionViewController

- (instancetype)initWithSubjectName:(NSString *)subjectName {
    self = [super init];
    if (self) {
        _subjectName = subjectName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [NSString stringWithFormat:@"添加%@问题", self.subjectName];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    
    self.answerLabelButton.text = @"长按语音录入";
    self.answerLabelButton.hidden = YES;
    self.view.backgroundColor = CMNormalBg;
    _questionTextView = [self assembleTextViewWithPlaceholder:@"请录入问题..."];
    _answerTextView = [self assembleTextViewWithPlaceholder:@"请录入答案..."];
    
    _questionTextView.frame = CGRectMake(20, 84, self.view.cWidth - 40, 90);
    _answerTextView.frame = CGRectMake(20, 194, self.view.cWidth - 40, 90);
    
    [self.view addSubview:_questionTextView];
    [self.view addSubview:_answerTextView];
    
    UIButton *saveButton = [[UIButton alloc] init];
    saveButton.frame = CGRectMake(20, CGRectGetMaxY(_answerTextView.frame) + 20, self.view.cWidth - 40, 46);
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setBackgroundColor:HEXCOLOR(0x42A8FF)];
    [saveButton addTarget:self action:@selector(saveSubjectItem) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveSubjectItem {
    if (self.questionTextView.text.length <= 0) {
        [self showErrorHud:@"没有录入问题"];
        return;
    }
    
    if (self.answerTextView.text.length <= 0) {
        [self showErrorHud:@"没有录入答案"];
        return;
    }
    IASubjectItem *subjectItem = [[IASubjectItem alloc] init];
    subjectItem.question = self.questionTextView.text;
    subjectItem.answer = self.answerTextView.text;
    subjectItem.subjectName = self.subjectName ?: @"地理";
    
    [IAMetaDataReader saveSubject:subjectItem completion:^(BOOL result) {
        if (self.completionBlock) {
            self.completionBlock();
            self.completionBlock = nil;
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
    self.answerLabelButton.hidden = YES;
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            self.speechContent = nil;
            [self startRecord];
            break;
        }
        case UIGestureRecognizerStateChanged: {
            break;
        }
            
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded: {
            [self stopRecord];
            break;
        }
            
        case UIGestureRecognizerStateFailed: {
            [self stopRecord];
            break;
        }
            
        default:
            break;
    }
}

- (YKTextView *)assembleTextViewWithPlaceholder:(NSString *)placeholder {
    YKTextView *textView = [[YKTextView alloc] init];
    textView.delegate = self;
    textView.backgroundColor = [UIColor whiteColor];
    textView.placehoder = placeholder;
    textView.inputAccessoryView = self.accessoryButton;
    return textView;
}

- (UIButton *)accessoryButton {
    if (!_accessoryButton) {
        UIButton *accessoryButton = [[UIButton alloc] init];
        accessoryButton.frame = CGRectMake(0, 0, self.view.cWidth, 46);
        accessoryButton.backgroundColor = CMColor(243, 243, 243);
        [accessoryButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [accessoryButton setTitle:@"语音录入" forState:UIControlStateNormal];
        [accessoryButton addTarget:self action:@selector(accessoryClick) forControlEvents:UIControlEventTouchUpInside];
        _accessoryButton = accessoryButton;
    }
    return _accessoryButton;
}

- (void)accessoryClick {
    [self.view endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.answerLabelButton.hidden = NO;
        [self.view bringSubviewToFront:self.answerLabelButton];
        
        if ([self.selectedTextView isEqual:self.questionTextView]) {
            self.answerLabelButton.text = @"长按语音录入问题";
        } else {
            self.answerLabelButton.text = @"长按语音录入答案";
        }
    });
}

- (void)textViewDidBeginEditing:(YKTextView *)textView {
    self.selectedTextView = textView;
}

- (void)onError:(IFlySpeechError *) errorCode {
    if (errorCode.errorCode != 0) { // 发生错误
        NSString *msg = errorCode.errorDesc;
        [self showErrorHud:msg];
    }
}

- (void)onResults:(NSArray *) results isLast:(BOOL)isLast {
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    NSString *resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    if (resultFromJson) {
        [self.speechContent appendString:resultFromJson];
    }
    
    if (isLast) {
        if (self.speechContent.length > 0) {
            if (self.selectedTextView.text.length > 0) {
                self.selectedTextView.text = [NSString stringWithFormat:@"%@%@", self.selectedTextView.text, self.speechContent];
            } else {
                self.selectedTextView.text = self.speechContent;
            }
            
        } else {
            // 语言听写失败 可能是录音时间太短...
            [self showErrorHud:@"语言听写失败, 录音时间太短..."];
        }
    }
}

- (NSMutableString *)speechContent {
    if (!_speechContent) {
        _speechContent = [NSMutableString string];
    }
    return _speechContent;
}

@end
